<?php

namespace app\index\service;

/**
 * Description of User
 *
 * @author Dongasai
 */
class User
{

    /**
     * 增加用户
     * @param type $uid 发起增加的用户
     * @param type $data 用户数据
     */
    public static function add($uid, $data)
    {
        //验证是否有增加权限
        $userModel        = \think\Loader::model("user");
        $data['password'] = md5($data['password']);
        $re               = $userModel->data($data)->save();
        if ($re) {
            return true;
        } else {
            return "写入数据库失败!";
        }
    }

    /**
     * 修改用户数据
     * @param type $uid 发起的用户
     * @param type $to_uid 修改的用户
     * @param type $data 数据
     */
    public static function edit($uid, $to_uid, $data)
    {
        //验证是否有修改的权限
        //进行数据组装
        if ($data['password']) {
            $data['password'] = md5($data['password']);
        }
        //进行变更
        $userModel = \think\Loader::model("user");
        $where     = [
            'id' => $to_uid
        ];
        $re        = $userModel->save($data, $where);
        if ($re) {
            return true;
        } else {
            return "更新数据失败!";
        }
    }

    /**
     * 分页获取
     * @param type $where
     * @param type $order
     * @param type $page
     * @param type $low
     */
    public static function listForPage($where, $order, $page, $low)
    {
        $userModel = \think\Loader::model("user");
        $list      = $userModel->where($where)->order($order)->page($page, $low)->select();
        $totle     = $userModel->where($where)->count();
        return ["list" => $list, 'totle' => $totle];
    }

    /**
     * 用户登陆
     * @param type $username
     * @param type $password
     * @param type $append
     */
    public static function login($username, $password, $append = [])
    {
        $userModel = \think\Loader::model("user");
        $userinfo  = $userModel->get(['username' => $username]);
        if ($userinfo) {
            //查询都信息继续操作
            //不对账户密码
            if (md5($password) === $userinfo['password']) {
                //登陆成功
                session('uid', $userinfo['id']);
                return $userinfo['id'];
            } else {
                //密码不对
                return "密码错误!";
            }
        } else {
            return "不存在的信息!!";
        }
    }

    /**
     * 获取用户信息
     * @param type $uid
     */
    public static function userinfo($uid)
    {
        if (empty($uid)) {
            return false;
        }
        $userModel = \think\Loader::model("user");
        $info      = $userModel->get(['id' => $uid]);
        if ($info) {
            return $info;
        } else {
            return false;
        }
    }

}
